<?php
require_once "Ticker.php";
define('AMUD_MAX_MESSAGES',50);
/**
 * Response class, holds response data.
 * @static
 * @package meta
 * @author alcaitiff
 */
class Response
{
	private $user,$entryTime;
    /**
     *
     * @param Player|Char $user User
     * @param int $entryTime Timestamp
     */
	public function __construct ($user,$entryTime=0){
		$this->user=$user;
        if($user!=null && $user->id!=null){
            $this->user->refresh(Ticker::getCurrentTick());
        }
		$this->entryTime=$entryTime;
	}
	/**
     * Magic Get
     * @param string $property
     * @return mixed
     */
    public function __get($property){
		return $this->$property;
	}
	/**
     * This function send the response direct to the output in order to prevent large strings in the php memory 
     * @return void
     */
    public function sendJSON(){
        header('content-type: application/json');
        if(isset($_REQUEST['callback'])){
            echo $_REQUEST['callback'].'(';
        }
		echo '{';
		//Errors
		echo '"errors":["';
		$messages=MessageSystem::getErrorMessages(AMUD_MAX_MESSAGES);
		echo implode('",'."\n\t".'"',$messages);
		echo '"],';
		//Messages
		echo "\n".'"messages":[';
		$messages=MessageSystem::getCharacterMessages(AMUD_MAX_MESSAGES);
		
		echo implode(','."\n\t",$this->arrayToJSON($messages));
		
		echo '],';
		//Debug
		echo "\n".'"debug":["';
		$messages=MessageSystem::getDebugMessages(AMUD_MAX_MESSAGES);
		if(MessageSystem::getDebug()){
			$now=microtime(true);
			$messages[]='Proccessing time: '.round($now-$this->entryTime,4).' seconds';
		}
		echo implode('",'."\n\t".'"',$messages);
		echo '"]';
		//User
        if($this->user->charId!=null){
            echo ",\n\n".'"user":'.$this->user->toJSON();
        }
       	echo '}';
        if(isset($_REQUEST['callback'])){
            echo ');';
        }
	}
    /**
     * Make an array of json messages
     * @param array $array
     * @return array
     */
	private function arrayToJSON($array){
		$ret=array();
		foreach($array as $v){
			if(is_object($v) && method_exists($v,'toJSON'))
				$ret[]=$v->toJSON();
			else
				$ret[]=json_encode($v);
		}
		return $ret;
	
	}
}